<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
const BRAND = '小鹏';
$db->delete('tDealer', ['sBrand' => BRAND]);
$client = new GuzzleHttp\Client(['timeout' => 0,]);
$jar = new \GuzzleHttp\Cookie\CookieJar();


$res = $client->get('https://www.xiaopeng.com/pengmetta.html?forcePlat=h5', ['cookies' => $jar]);
$html = (string)$res->getBody();


$ok = preg_match('/"csrf":"(.*?)"/', $html, $m);
if ($ok) {
    $csrf = $m[1];

    $res = $client->post('https://www.xiaopeng.com/api/store/queryAll', [
        'json' => [
            'lat' => '36.66477',
            'lng' => '117.14632',
            '_csrf' => $csrf,
        ],

        'cookies' => $jar,
        'headers' => [
            'content-type' => 'application/json;charset=UTF-8',
            'referer' => ' https://www.xiaopeng.com/pengmetta.html?forcePlat=h5',
            'user-agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        ]
    ]);
    $html = (string)$res->getBody();
    $data = json_decode($html, true);
    $dealers = $data['data'];
    foreach ($dealers as $item) {

        $db->insert('tDealer', [
            'sDealerName' => $item['storeName'],
            'nBrandID' => $item['storeCode'],
            'sBrand' => BRAND,
            'sProvince' => $item['provinceName'],
            'sCity' => $item['cityName'],
            'sAddress' => $item['address'],
            'sSaleCall' => $item['mobile'],
            'sLatitude' => $item['lat'],
            'sLongitude' => $item['lng'],
            'dUpdateTime' => Medoo::raw('now()'),
            'sManufacturer' => BRAND,
        ]);
        echo "{$item['storeName']}完成" . PHP_EOL;
    }
    echo '爬虫结束' . PHP_EOL;
}
